package controllers

import (
	//ex "errors"
	"github.com/revel/revel"
	"waterblabla/app/models"
)

type Dev struct {
	Controller
}

// 设备提交绑定请求
func (c Dev) Bind() revel.Result {
	// parse
	type Req struct {
		Sn string
		Qid string
		VersionCode string
	}
	
	var req Req
	if err := models.ParseBodyAndValidate(c.body, &req); err != nil {
		return c.RenderResult(err)
	}
	// determine wether the specified sn is ours
	if err := models.ValidateSn(req.Sn); err != nil {
		return c.RenderResult(err)
	}

	if err := models.AddDev(req.Sn); err != nil {
		return c.RenderResult(err)
	}

	return c.RenderResult(struct {
		HbInterval int `json:"hbInterval"`
	}{HbInterval: int(models.HbInterval)})
}

func (c Dev) Call() revel.Result {
	// parse
	var sn string
	if err := models.ParseBodyAndValidate(c.body, &struct {
		Sn *string `json:"sn" valid:"Required"`
	}{&sn}); err != nil {
		return c.RenderResult(err)
	}

	return c.RenderResult(models.AddOrder(sn))
}

func (c Dev) Heartbeat() revel.Result {
	// parse
	var sn string
	if err := models.ParseBodyAndValidate(c.body, &struct {
		Sn *string `json:"sn" valid:"Required"`
	}{&sn}); err != nil {
		return c.RenderResult(err)
	}

	if err := models.HeartBeat(sn); err != nil {
		return c.RenderResult(err)
	}

	return c.RenderResult(struct {
		HbInterval int `json:"hbInterval"`
	}{HbInterval: int(models.HbInterval)})
}

/*
// 水站提交绑定sn请求
func (c Dev) HasBinded() revel.Result {
	type Req struct {
		models.QS `,inline valid:"Required"`
		Sn        string `json:"sn" valid:"Required"`
	}
	var req Req
	if err := models.ParseBodyAndValidate(c.body, &req); err != nil {
		return c.RenderResult(err)
	}
	//	state, err := models.HasBinded_usr(req.Qid, req.Sn)
	//	if state != models.UNBIND && state != models.DEVSTUB && state != models.USERSTUB {
	//		return c.RenderResult(err)
	//	}
	models.DelContract(req.Qid, req.Sn)
	return c.RenderResult(nil)
}

// 水站提交解绑请求

func (c Dev) UnbindSn() revel.Result {
	type Req struct {
		models.QS `,inline valid:"Required"`
		Sn        string `json:"sn" valid:"Required"`
	}
	var req Req
	if err := models.ParseBodyAndValidate(c.body, &req); err != nil {
		return c.RenderResult(err)
	}

	return c.RenderResult(models.UnBind(req.Qid, req.Sn))
}*/
